package com.sgb.kjwl.view.ui.fragment.transport;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.sgb.kjwl.AppFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragFreightCarTransportationBinding;
import com.sgb.kjwl.model.entity.self.GoodsManageItemData;
import com.sgb.kjwl.model.entity.transport.CarrierBusinessEntity;
import com.sgb.kjwl.model.entity.transport.TrucksCarrier;
import com.swgk.core.util.PermissionCheckUtil;
import com.swgk.core.util.UserOperating;
import com.sgb.kjwl.view.constant.RouterKey;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LogisticsEvent;
import com.sgb.kjwl.view.ui.activity.self.logistics.CargoManageActivity;
import com.sgb.kjwl.view.ui.activity.self.logistics.InquiryActivity;
import com.sgb.kjwl.view.ui.activity.transport.CarriageDetailActivity;
import com.sgb.kjwl.view.ui.adapter.transport.owner.FreightCarTransportationAdapter;
import com.swgk.core.dialog.RoundDialog;
import com.sgb.kjwl.viewmodel.transport.FreightCarTransportationModel;
import com.swgk.core.util.ClickUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FreightCarTransportationFragment extends AppFragment {

    FragFreightCarTransportationBinding binding;
    //货源列表
    private List<TrucksCarrier> mList;
    private FreightCarTransportationAdapter mAdapter;

    private boolean isGeneralGoods = true;
    private boolean isCompanyAuth = true;
    private int pattern = 0;
    private int tabPosition = 0;
    private int listcount = 0;
    int page = 1;
    private FreightCarTransportationModel mModel;
    Map<String, Object> map = new HashMap<>();

    public static FreightCarTransportationFragment newInstance(int tabPosition, boolean isGeneralGoods, boolean isCompanyAuth) {
        FreightCarTransportationFragment fragment = new FreightCarTransportationFragment();
        Bundle args = new Bundle();
        args.putInt(RouterKey.TYPE, tabPosition);
        args.putBoolean(RouterKey.BOOLEAN, isGeneralGoods);
        args.putBoolean(RouterKey.DATA1, isCompanyAuth);
        fragment.setArguments(args);
        return fragment;
    }
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.frag_freight_car_transportation, container, false);
        binding.setLifecycleOwner(this);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mModel = new ViewModelProvider(this).get(FreightCarTransportationModel.class);
        initView();
    }
    private void initView(){
        initIntentParams();
        initRecycler();
        initEvent();
       // mModel.getList(getContext(),1,tabPosition);
        mModel.mCarrierBusinessEntityMutableLiveData.observe(getViewLifecycleOwner(), list -> {
            refreshUIByData(list);
        });
    }
    private void initIntentParams() {
        tabPosition = getArguments().getInt(RouterKey.TYPE);
        isGeneralGoods = getArguments().getBoolean(RouterKey.BOOLEAN);
        isCompanyAuth = getArguments().getBoolean(RouterKey.DATA1);
        pattern = isGeneralGoods ? 0 : 1;
    }

    private void initRecycler() {
        mList = new ArrayList<>();
        mAdapter = new FreightCarTransportationAdapter(mList);
        binding.rvFragFreight.setLayoutManager(new LinearLayoutManager(getActivity()));
        mAdapter.bindToRecyclerView(binding.rvFragFreight);
    }

    private void initEvent() {
        binding.srlFragFreightCar.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page += 1;
                mModel.getList(getContext(),page);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                mModel.getList(getContext(),page);
            }
        });
        mAdapter.setListener(new FreightCarTransportationAdapter.GoodsOperationListener() {
            @Override
            public void OnitemClick(TrucksCarrier info) {
                CarriageDetailActivity.start(getContext(),info.getCarrierNo(),1);
            }

            @Override
            public void OnInquiryClick(TrucksCarrier info) {
                if (!ClickUtils.isDoubleClick()) {
                    if (UserOperating.getInstance().isNotOpenFundAccount(getContext(), PermissionCheckUtil.KEY_WODEXUNJIA)) {
                        return;
                    }
                    goInquiry(info);
                }
            }

            @Override
            public void CallPhone(TrucksCarrier info) {
                showConsignorDialog(info.getTelphone());
            }

            @Override
            public void goHome(TrucksCarrier info) {

            }
        });

    }


    /**
     * 同步数据
     */
    public void refreshUIByData(CarrierBusinessEntity listResponse) {
        binding.srlFragFreightCar.finishRefresh();
        binding.srlFragFreightCar.finishLoadMore();

        if (listResponse.getPage().getRecords() != null) {
            if (page==1){
                mList.clear();
            }
            mList.addAll(listResponse.getPage().getRecords());
        }
        if (listResponse.getPage().getPageNumber()>listResponse.getPage().getTotalPage()){
            binding.srlFragFreightCar.setNoMoreData(listResponse.getPage().isLastPage());
        }
        mAdapter.setEmptyView(R.layout.layout_null_list_logistics);
        mAdapter.notifyDataSetChanged();
        setTableCount(isGeneralGoods ? listResponse.getNormalStatusNum() : listResponse.getNormalStatusNum());
    }

    public void deleteInfoSuccess(GoodsManageItemData recordsBean) {
        mAdapter.getData().remove(recordsBean);
        mAdapter.notifyDataSetChanged();
        setTableCount(listcount == 0 ? listcount : listcount - 1);
    }

    public void setTableCount(int count) {
        //只有第2个tab有数字
        if (tabPosition == 1) {
            listcount = count;
            EventBus.getDefault().post(LogisticsEvent.make(EventConstant.EVENT_REFRESH_CAR_TRANSPORT, count));
        }
    }
    public void refreshData(){
        //onLazyLoad();
        initView();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof CargoManageActivity) {
        }
    }
    private void goInquiry(TrucksCarrier info){
        //TODO 去询价界面
        InquiryActivity.startCarriageInquiry(getContext(),info.getCarrierNo(),info.getTelphone());
    } //打电话弹窗
    public void showConsignorDialog(String phone) {
        new RoundDialog.Builder(getContext())
                .title("确认呼叫")
                .content(phone)
                .cancel("取消")
                .confirm("确定")
                .contentGravity(Gravity.CENTER)
                .cancelable(false)
                .confirmCallback(new RoundDialog.SingleCallback() {
                    @Override
                    public void onClick(View v) {
                        callPhone(phone);
                    }
                })
                .show();
    }
    protected void callPhone(String phoneNum) {
        Intent intent = new Intent(Intent.ACTION_DIAL);
        Uri data = Uri.parse("tel:" + phoneNum);
        intent.setData(data);
        startActivity(intent);
    }
}
